<template>
    <div class="wraps">
        <div ref="bar" class="bar"></div>
    </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue'
let speed = ref<number>(1)
let bar = ref<HTMLElement>()
let timer = ref<number>(0)
const startLoading = () => {
    let dom = bar.value as HTMLElement
    speed.value = 1;
    timer.value = window.requestAnimationFrame(function fn() {
        if (speed.value < 90) {
            speed.value += 1;
            dom.style.width = speed.value + "%"
            // 这个方法的作用是向浏览器发送请求我希望你稍后调用函数fn()，fn函数后面还有程序要执行后才可能执行fn函数
            // requestAnimationFrame()发起请求后多长时间后浏览器响应是不确定的
            timer.value = window.requestAnimationFrame(fn)
        } else {
            speed.value = 1;
            window.cancelAnimationFrame(timer.value)
        }
    })


}
const endLoading = () => {
    let dom = bar.value as HTMLElement; setTimeout(() => {
        window.requestAnimationFrame(() => {
            speed.value = 100;
            dom.style.width = speed.value + "%"
        })
    }, 900)

}


defineExpose({
    startLoading, endLoading
})

</script>

<style scoped lang="scss">
.wraps {
    position: fixed;
    top: 0;
    width: 100%;
    height: 5px;
}

.bar {
    height: inherit;
    width: 0;
    background: #409eff;
}
</style>